import axios from 'axios'
import { useUserStoreHook, useUserStore } from '@/store/modules/user'
import { message } from "ant-design-vue";
import router from '@/router'

// 创建请求实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStoreHook()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    if (userStore.userInfo) {
      config.headers.user_id = userStore.userInfo.userId
      config.headers.username = userStore.userInfo.userName
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const { code, ok, msg } = response.data
    if (ok || code === 200 || code === 302) {
      return response.data
    }
    if (code === 517 || msg === '令牌不能为空') {
      const userStore = useUserStore()
      userStore.logout() // 清除个人基本信息
      router.push('/login')
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof Blob) {
      return response.data
    }
    message.error(msg || '服务器出错啦')
    return Promise.reject(new Error(msg || 'Error'))
  },
  (error) => {
    const { response } = error
    const { message } = error
    message.error(message || '服务器出错啦')
    if (response && response.data) {
      return Promise.reject(error)
    }
    return Promise.reject(error)
  },
)

/**
 * 封装post请求
 * @param {string} url - api参数
 * @param {JSON} data - 参数
 * @param {string} type - 类型
 * @returns {Promise} - promise
 */

export const post = (url, data = {}, type) => {
  if (type === 'export') {
    instance.defaults.responseType = 'blob'
    instance.defaults.headers['Content-Type'] = 'application/json'
  } else if (type === 'import') {
    instance.defaults.headers['Content-Type'] = 'multipart/form-data'
  } else {
    instance.defaults.responseType = 'json'
    instance.defaults.headers['Content-Type'] = 'application/json'
  }
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(
      (response) => {
        if (response && (response.type === 'application/json' || response.type === 'application/json; charset=utf-8')) {
          let reader = new FileReader()
          reader.readAsText(response.data || response, 'utf-8')
          reader.onload = () => {
            let text = reader.result
            let jsonText = JSON.parse(text)
            response = jsonText
            resolve(response)
            return
          }
        } else {
          resolve(response)
        }
      },
      (err) => {
        reject(err)
      },
    )
  })
}

/**
 * 封装get方法
 * @param {string} url - api路径
 * @param {JSON} data - 参数
 * @param {string} type - 类型
 * @returns {Promise} - promise
 */
export const get = (url, data = {}, type) => {
  if (type === 'export') {
    instance.defaults.responseType = 'blob'
    instance.defaults.headers['Content-Type'] = 'application/json'
  } else {
    instance.defaults.responseType = 'json'
    instance.defaults.headers['Content-Type'] = 'application/json'
  }
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: data,
      })
      .then((response) => {
        if (response && (response.type === 'application/json' || response.type === 'application/json; charset=utf-8')) {
          let reader = new FileReader()
          reader.readAsText(response.data, 'utf-8')
          reader.onload = () => {
            let text = reader.result
            let jsonText = JSON.parse(text)
            response.data = jsonText
            resolve(response)
            return
          }
        } else {
          resolve(response)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export const put = (url, data = {}, type) => {
  if (type === 'export') {
    instance.defaults.responseType = 'blob'
    instance.defaults.headers['Content-Type'] = 'application/json'
  } else {
    instance.defaults.responseType = 'json'
    instance.defaults.headers['Content-Type'] = 'application/json'
  }
  return new Promise((resolve, reject) => {
    instance.put(url, data).then(
      (response) => {
        if (response && (response.type === 'application/json' || response.type === 'application/json; charset=utf-8')) {
          let reader = new FileReader()
          reader.readAsText(response.data, 'utf-8')
          reader.onload = () => {
            let text = reader.result
            let jsonText = JSON.parse(text)
            response = jsonText
            resolve(response)
            return
          }
        } else {
          resolve(response)
        }
      },
      (err) => {
        reject(err)
      },
    )
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export const _delete = (url, params = {}) => {
  return instance({
    method: 'delete',
    url,
    params,
  })
}

export default instance
